package cn.com.picc.equipment.common.config.actuatorConfig;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.actuate.trace.http.HttpTrace;
import org.springframework.boot.actuate.trace.http.HttpTraceRepository;

import java.util.Collections;
import java.util.List;

@Slf4j
public class RemoteHttpTraceRepository implements HttpTraceRepository {

    private static final String NEED_TRACE_PATH_PREFIX = "/ite";
    private static final String IGNORE_CONTENT_TYPE = "multipart/form-data";

    @Override
    public List<HttpTrace> findAll() {
        return Collections.emptyList();
    }

    @Override
    public void add(HttpTrace trace) {
        String path = trace.getRequest().getUri().getPath();
        HttpTrace.Request request = trace.getRequest();
        if (path.startsWith(NEED_TRACE_PATH_PREFIX)) {
            log.info(path);
        }
/**
        if (path.startsWith(NEED_TRACE_PATH_PREFIX) && !Objects.equals(IGNORE_CONTENT_TYPE, request.getContentType())) {

            String requestBody = IOUtils.toString(request.getInputStream(), Charsets.UTF_8);
            log.info(requestBody);
            //1. 记录日志
            HttpTraceLog traceLog = new HttpTraceLog();
            traceLog.setPath(path);
            traceLog.setMethod(request.getMethod());
            long latency = System.currentTimeMillis() - startTime;
            traceLog.setTimeTaken(latency);
            traceLog.setTime(LocalDateTime.now().toString());
//                traceLog.setParameterMap(JsonMapper.builder()..ToObject(request.getParameterMap()));
            traceLog.setStatus(status);
            traceLog.setRequestBody(getRequestBody(request));
            traceLog.setResponseBody(getResponseBody(response));
            log.info(traceLog.toString());
//                log.info("Http trace log: {}", JsonMapper.INSTANCE.toJson(traceLog));
        }
**/

        String queryPara = trace.getRequest().getUri().getQuery();
        String queryParaRaw = trace.getRequest().getUri().getRawQuery();
        String method = trace.getRequest().getMethod();
        log.info("*****************************"+method);
        if(method.equals("POST")) {
            log.info("*****************************");
        }
        long timeTaken = trace.getTimeTaken();
        String time = trace.getTimestamp().toString();
        log.info("path: {}, queryPara: {}, queryParaRaw: {}, timeTaken: {}, time: {}, method: {}", path, queryPara, queryParaRaw,
            timeTaken, time, method);
    }

    @Data
    private static class HttpTraceLog {

        private String path;
        private String parameterMap;
        private String method;
        private Long timeTaken;
        private String time;
        private Integer status;
        private String requestBody;
        private String responseBody;
    }
}
